//
//  AppDelegate.swift
//  sinaWeibo
//
//  Created by apple on 16/2/26.
//  Copyright © 2016年 Qifeng Yan. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        
        setupAppearance()
        
        let account = QFUserAccountViewModel.sharedInstance.userAccount
        print("我在AppDelegate里面获取到账户：\(account)")
        
        // 创建window
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        
        // 指定根控制器
        window?.rootViewController = defaultsViewController()
//        // 设置背景颜色
//        window?.rootViewController?.view.backgroundColor = UIColor.redColor()
        
        // 显示界面
        window?.makeKeyAndVisible()
        
        QFUserAccountViewModel.sharedInstance.isUserLogin
        
        return true
    }
    
    // MARK: - 默认控制器
    private func defaultsViewController() -> UIViewController {
        // 如果用户没有登陆
        if !QFUserAccountViewModel.sharedInstance.isUserLogin {
            return QFTabBarController()
        }
        
        // 如果用户登陆了 判断是否是新版本是 就跳转到新特性界面 不是 就跳转欢迎界面
        return isNewVersion() ? QFNewFeatureViewController() :QFWelcomeViewController()
    }
    
    // MARK: - 跳转控制器
    private func switchRootViewController(isTrue: Bool) {
        window?.rootViewController = isTrue ? QFTabBarController() : QFWelcomeViewController()
    }
    
    /// 提供一个外部调用的方法 来跳转控制器
    class func outSwitchRootViewController(isTrue: Bool) {
        let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
        appDelegate.switchRootViewController(isTrue)
    }
    
    // MARK: - 设置全局的barButtonItem字体颜色
    private func setupAppearance() {
        UIBarButtonItem.appearance().tintColor = UIColor.orangeColor()
    }
    
    // 判断是否是新版本
    private func isNewVersion() -> Bool {
        let version = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String
        
        let versionKey = "versionKey"
        let newVersion = NSUserDefaults.standardUserDefaults().stringForKey(versionKey)
        
        let isNew =  version != newVersion
        
        if isNew {
            NSUserDefaults.standardUserDefaults().setObject(version, forKey: "versionKey")
            NSUserDefaults.standardUserDefaults().synchronize()
        }
        
        return isNew
    }
    

}

